import * as types from "./actionType";

export interface StateProps {
  id: number;
  text: string;
  isFinished: boolean; //是否已完成
}

export interface ActionProps {
  type: string;
  [key: string]: any;
}
//state当前的状态   action描述应该如何修改state对象
const reducer = (state: StateProps[] = [], action: ActionProps) => {
  switch (action.type) {
    //添加
    case types.ADD:
      return [...state, action.todo];
    //是否完成
    case types.CHANGEFINISHED:
      return state.map((item) => {
        if (item.id === action.id) {
          return Object.assign({}, item, {
            isFinished: !item.isFinished,
          });
        }
        window.localStorage.setItem("data", JSON.stringify(state));

        console.log(item);
        return item;
      });
    //删除
    case types.DEL:
      state.splice(action.index, 1);
      window.localStorage.setItem("data", JSON.stringify(state));
      console.log(state);
      return [...state];

    //初始状态init，数据从localStorge调取
    case types.INIT:
      console.log(action);
      return action.todo;

    default:
      return state;
  }
};

export type RootState = ReturnType<typeof reducer>;

export default reducer;
